package com.lzx.lizhenxing.common.interceptor;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lzx.lizhenxing.common.annotation.NoLogin;
import com.lzx.lizhenxing.common.constrants.CommonConstants;
import com.lzx.lizhenxing.common.exception.CommonException;
import com.lzx.lizhenxing.common.utils.JwtUtils;
import com.lzx.lizhenxing.common.utils.RedisUtils;
import com.lzx.lizhenxing.common.utils.UserUtils;
import com.lzx.lizhenxing.sys.enums.UserKeyEnum;
import io.jsonwebtoken.Claims;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 控制层的方法内部封装成HandlerMethod对象
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 判断方法是否使用了指定的注解
        // 该注解表示未登录即可访问
        if (method.isAnnotationPresent(NoLogin.class)) {
            return true;
        }

        String token = request.getHeader("Authorization");
        // 前端没有传token
        if (token == null || token.isEmpty()) {
            throw new CommonException(CommonConstants.NO_LOGIN, "请先登录");
        }
        // 解析失败，说明jwt过期或者被篡改
        Claims claims = null;
        try {
            claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            throw new CommonException(CommonConstants.NO_LOGIN, "请先登录");
        }
        Long uid = (Long) claims.get("uid");
        // redis中的token也要做判断
        try {
            String value = (String) RedisUtils.getValue(UserKeyEnum.USER_TOKEN.getKey() + uid.toString());
            if(StringUtils.isBlank(value)){
                throw new CommonException(CommonConstants.NO_LOGIN, "请先登录");
            }
        } catch (Exception e) {
            throw new CommonException(CommonConstants.NO_LOGIN, "请先登录");
        }
        // 向ThreadLocal中储存用户id,后续会经常使用
        UserUtils.setUser(uid);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 从ThreadLocal中删除用户id
        UserUtils.removeUser();
    }
}
